package com.mxdx.edu.common;

import com.mxdx.edu.common.log.AppLogger;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: liujianlu
 * @Description:
 * @Date: Created in 20:18 2018/7/30
 */
public class VnHttpConnector {

   private static AppLogger logger = new AppLogger(VnHttpConnector.class);

    public static final String METHOD_TYPE_GET = "GET";
    public static final String METHOD_TYPE_POST = "POST";
    public static final String RET_HEAD = "HEAD";
    public static final String RET_STATUS = "STATUS";
    public static final String RET_MESSAGE = "MESSAGE";

    public VnHttpConnector() {
    }

    public static Map<String, Object> request(String url, byte[] data, String methodType, int timeout, JSONObject header) throws HttpException, IOException {
        timeout *= 1000;
        HashMap response = new HashMap();
        Object method = null;
        HttpClient client = new HttpClient();
        try {
            ByteArrayRequestEntity key;
            if("GET".equals(methodType)) {
                GetMethod status = new GetMethod(url);
                if(data != null && data.length > 0) {
                    status.setQueryString(new String(data));
                }

                method = status;
            } else {
                PostMethod status1 = new PostMethod(url);
                if(data != null && data.length > 0) {
                    key = new ByteArrayRequestEntity(data);
                    status1.setRequestEntity(key);
                }
                method = status1;
            }

            ((HttpMethod)method).getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false));
            if(header != null) {
                Iterator status2 = header.keySet().iterator();
                key = null;
                String value = null;

                while(status2.hasNext()) {
                    String key1 = (String)status2.next();
                    value = (String)header.get(key1);
                    ((HttpMethod)method).setRequestHeader(key1, value);
                }
            }

            client.getParams().setSoTimeout(timeout);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
            int status3 = client.executeMethod((HttpMethod)method);
            response.put("STATUS", Integer.valueOf(status3));
            response.put("MESSAGE", ((HttpMethod)method).getResponseBody());
            response.put("HEAD", header2Map(((HttpMethod)method).getResponseHeaders()));
        } finally {
            if(method != null) {
                ((HttpMethod)method).releaseConnection();
            }

            client = null;
        }
        return response;
    }

    public static Map<String, Object> doPost(String url, byte[] json, int timeout, JSONObject header) {
        CloseableHttpClient httpClient = createSSLInsecureClient();
        HttpPost post = new HttpPost(url);
        String encoding = "UTF-8";
        Iterator response;
        if(header != null) {
            header.remove("content-length");
            response = header.keySet().iterator();
            String data = null;
            String e = null;

            while(response.hasNext()) {
                data = (String)response.next();
                e = (String)header.get(data);
                post.setHeader(data, e);
            }
        }

        response = null;
        HashMap data1 = new HashMap();

        try {
            RequestConfig e1 = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
            post.setConfig(e1);
            String jsonString = new String(json, encoding);
            StringEntity entity = new StringEntity(jsonString, encoding);
            post.setEntity(entity);
            CloseableHttpResponse response1 = httpClient.execute(post);
            HttpEntity httpEntity = response1.getEntity();
            byte[] retmessage = new byte[0];
            int msgLen = response1.getEntity().getContent().available();
            retmessage = new byte[msgLen];
            retmessage = VnHttpForwardHanlder.InputStreamToByte(httpEntity.getContent());
            data1.put("MESSAGE", retmessage);
            data1.put("HEAD", httpsheader2Map(response1.getAllHeaders()));
            data1.put("STATUS", Integer.valueOf(response1.getStatusLine().getStatusCode()));
        } catch (UnsupportedEncodingException var26) {
            logger.error("编码格式输入错误", var26);
            throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + encoding);
        } catch (ClientProtocolException var27) {
            var27.printStackTrace();
        } catch (IOException var28) {
            logger.error("读取流文件异常", var28);
            throw new RuntimeException("读取流文件异常", var28);
        } catch (Exception var29) {
            logger.error("通讯未知系统异常", var29);
            throw new RuntimeException("通讯未知系统异常", var29);
        } finally {
            if(httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException var25) {
                    var25.printStackTrace();
                }
            }

        }

        return data1;
    }

    public static Map<?, ?> request(String url, byte[] data, String methodType, int timeout, String jsonFmtHeaders) throws HttpException, IOException {
        return request(url, data, methodType, timeout, JSONObject.fromObject(jsonFmtHeaders));
    }

    public static Map<?, ?> request(String url, byte[] data, String methodType, int timeout) throws HttpException, IOException {
        return request(url, data, methodType, timeout, (JSONObject)null);
    }

    private static Map<String, String> header2Map(Header[] headers) {
        HashMap tmp = null;
        if(headers != null) {
            tmp = new HashMap();
            Header[] var5 = headers;
            int var4 = headers.length;

            for(int var3 = 0; var3 < var4; ++var3) {
                Header header = var5[var3];
                tmp.put(header.getName(), header.getValue());
            }
        }

        return tmp;
    }

    private static Map<String, String> httpsheader2Map(org.apache.http.Header[] headers) {
        HashMap tmp = null;
        if(headers != null) {
            tmp = new HashMap();
            org.apache.http.Header[] var5 = headers;
            int var4 = headers.length;

            for(int var3 = 0; var3 < var4; ++var3) {
                org.apache.http.Header header = var5[var3];
                tmp.put(header.getName(), header.getValue());
            }
        }

        return tmp;
    }

    public static CloseableHttpClient createSSLInsecureClient() {
        try {
            SSLContext e = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(e, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(sslcsf).build();
        } catch (KeyManagementException var2) {
            var2.printStackTrace();
        } catch (NoSuchAlgorithmException var3) {
            var3.printStackTrace();
        } catch (KeyStoreException var4) {
            var4.printStackTrace();
        }

        return HttpClients.createDefault();
    }
}
